package com.itheima.controller;

import com.itheima.admin.employeepojo.vo.EmployeePageVo;
import com.itheima.common.JsonResult;
import com.itheima.admin.employeepojo.Employee;
import com.itheima.admin.AdminPage;
import com.itheima.admin.employeepojo.vo.EmployeeByIdVo;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wuzhiyong
 */
@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登陆
     *
     * @param employee employee
     * @return JsonResult
     */
    @PostMapping(value = "/login")
    public JsonResult<Object> login(@RequestBody Employee employee) {
        return employeeService.login(employee);
    }

    /**
     * 登出
     *
     * @param request request
     * @return JsonResult
     */
    @PostMapping(value = "/logout")
    public JsonResult<String> logout(HttpServletRequest request) {
        return employeeService.logout(request);
    }

    /**
     * 分页查询
     *
     * @param name     name
     * @param page     page
     * @param pagesize pagesize
     * @return JsonResult
     */
    @GetMapping(value = "/page")
    public JsonResult<AdminPage<EmployeePageVo>> employeePage(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "page") Integer page, @RequestParam(value = "pageSize") Integer pagesize) {
        AdminPage<EmployeePageVo> employeePage = employeeService.getPage(name, page, pagesize);
        return JsonResult.success(employeePage, null);

    }

    /**
     * 根据id查询
     *
     * @param id id
     * @return JsonResult
     */
    @GetMapping("/{id}")
    public JsonResult<EmployeeByIdVo> employeeId(@PathVariable("id") String id) {
        EmployeeByIdVo employeeByIdVo = employeeService.getByIdEmployee(id);
        if (employeeByIdVo != null) {
            return JsonResult.success(employeeByIdVo, null);
        }
        return JsonResult.error("暂无数据");
    }

    /**
     * 启用/禁用/修改
     *
     * @param employee employee
     * @return JsonResult
     */
    @PutMapping
    public JsonResult<String> employeeModify(@RequestBody Employee employee) {
        return employeeService.modifyEmployee(employee) ? JsonResult.success("员工信息修改成功", null) : JsonResult.error("修改失败" + " " + employee.getUsername() + " " + "已存在");
    }

    /**
     * 新增
     *
     * @param employee employee
     * @return JsonResult
     */
    @PostMapping()
    public JsonResult<Object> employeeAdd(@RequestBody Employee employee) {
        return employeeService.addEmployee(employee)?JsonResult.success(null, "添加成功"):JsonResult.error(employee.getUsername() + "已存在");
    }

}
